from flask import Blueprint, request, jsonify, url_for, render_template
from flask_login import current_user, login_required
from models import QuotationCart, QuotationCartItem, Product, ProductDetail,    Quotation,    QuotationItem,
from extensions import db
import datetime

cart_bp = Blueprint("cart", __name__)


@cart_bp.route("/add_to_cart", methods=["POST"])
@login_required
def add_to_cart():
    try:
        data = request.get_json()
        product_ids = data.get("product_ids", [])
        if not product_ids:
            return jsonify({"success": False, "message": "未选择任何产品"}), 400

        cart = QuotationCart.query.filter_by(user_id=current_user.id).first()
        if not cart:
            cart = QuotationCart(user_id=current_user.id)
            db.session.add(cart)
            db.session.flush()

        added_count = 0
        for product_id in product_ids:
            product_details = ProductDetail.query.filter_by(product_id=product_id).all()
            if not product_details:
                continue  # 跳过无规格的产品

            for detail in product_details:
                existing_item = QuotationCartItem.query.filter_by(
                    cart_id=cart.id, product_id=product_id, product_detail_id=detail.id
                ).first()
                if not existing_item:
                    cart_item = QuotationCartItem(
                        cart_id=cart.id,
                        product_id=product_id,
                        product_detail_id=detail.id,
                        quantity=1,
                    )
                    db.session.add(cart_item)
                    added_count += 1

        db.session.commit()
        return jsonify(
            {"success": True, "message": f"成功添加 {added_count} 个产品规格到购物车"}
        )
    except Exception as e:
        db.session.rollback()
        return jsonify({"success": False, "message": f"添加失败：{str(e)}"}), 500




@cart_bp.route("/cart")
@login_required
def cart():
    cart = QuotationCart.query.filter_by(user_id=current_user.id).first()
    cart_items = []
    if cart:
        cart_items = QuotationCartItem.query.filter_by(cart_id=cart.id).all()
    return render_template("cart.html", cart_items=cart_items)


@cart_bp.route("/update_cart_item", methods=["POST"])
@login_required
def update_cart_item():
    try:
        data = request.get_json()
        cart_item_id = data.get("cart_item_id")
        quantity = data.get("quantity")
        if not cart_item_id or not quantity:
            return jsonify({"success": False, "message": "缺少必要参数"}), 400

        cart_item = QuotationCartItem.query.get(cart_item_id)
        if not cart_item or cart_item.cart.user_id != current_user.id:
            return jsonify({"success": False, "message": "无权限或购物车项不存在"}), 403

        if quantity <= 0:
            db.session.delete(cart_item)
        else:
            cart_item.quantity = quantity

        db.session.commit()
        return jsonify({"success": True, "message": "数量更新成功"})
    except Exception as e:
        db.session.rollback()
        return jsonify({"success": False, "message": f"更新失败：{str(e)}"}), 500


@cart_bp.route("/delete_cart_item", methods=["POST"])
@login_required
def delete_cart_item():
    try:
        data = request.get_json()
        cart_item_id = data.get("cart_item_id")
        if not cart_item_id:
            return jsonify({"success": False, "message": "缺少必要参数"}), 400

        cart_item = QuotationCartItem.query.get(cart_item_id)
        if not cart_item or cart_item.cart.user_id != current_user.id:
            return jsonify({"success": False, "message": "无权限或购物车项不存在"}), 403

        db.session.delete(cart_item)
        db.session.commit()
        return jsonify({"success": True, "message": "删除成功"})
    except Exception as e:
        db.session.rollback()
        return jsonify({"success": False, "message": f"删除失败：{str(e)}"}), 500


@cart_bp.route("/add_to_cart", methods=["POST"])
@login_required
def add_to_cart():
    try:
        data = request.get_json()
        product_ids = data.get("product_ids", [])
        if not product_ids:
            return jsonify({"success": False, "message": "未选择任何产品"}), 400

        cart = QuotationCart.query.filter_by(user_id=current_user.id).first()
        if not cart:
            cart = QuotationCart(user_id=current_user.id)
            db.session.add(cart)
            db.session.flush()

        added_count = 0
        for product_id in product_ids:
            product_details = ProductDetail.query.filter_by(product_id=product_id).all()
            if not product_details:
                continue

            for detail in product_details:
                existing_item = QuotationCartItem.query.filter_by(
                    cart_id=cart.id, product_id=product_id, product_detail_id=detail.id
                ).first()
                if not existing_item:
                    cart_item = QuotationCartItem(
                        cart_id=cart.id,
                        product_id=product_id,
                        product_detail_id=detail.id,
                        quantity=1,
                    )
                    db.session.add(cart_item)
                    added_count += 1

        db.session.commit()
        return jsonify(
            {"success": True, "message": f"成功添加 {added_count} 个产品规格到购物车"}
        )
    except Exception as e:
        db.session.rollback()
        return jsonify({"success": False, "message": f"添加失败：{str(e)}"}), 500


@cart_bp.route("/generate_quotation")
@login_required
def generate_quotation():
    cart = QuotationCart.query.filter_by(user_id=current_user.id).first()
    cart_items = []
    if cart:
        cart_items = QuotationCartItem.query.filter_by(cart_id=cart.id).all()
    return render_template("cart/generate_quotation.html", cart_items=cart_items)


@cart_bp.route("/create_quotation", methods=["POST"])
@login_required
def create_quotation():
    try:
        cart = QuotationCart.query.filter_by(user_id=current_user.id).first()
        if not cart:
            return jsonify({"success": False, "message": "购物车为空"}), 400

        cart_items = QuotationCartItem.query.filter_by(cart_id=cart.id).all()
        if not cart_items:
            return jsonify({"success": False, "message": "购物车为空"}), 400

        # 生成唯一报价单编号
        quotation_number = (
            f"QT-{current_user.id}-{datetime.datetime.now().strftime('%Y%m%d%H%M%S')}"
        )

        # 创建报价单
        quotation = Quotation(
            user_id=current_user.id, quotation_number=quotation_number, status="draft"
        )
        db.session.add(quotation)
        db.session.flush()

        # 复制购物车项到报价单项
        for item in cart_items:
            detail = ProductDetail.query.get(item.product_detail_id)
            unit_price = detail.price if detail and detail.price else 0.0
            quotation_item = QuotationItem(
                quotation_id=quotation.id,
                product_id=item.product_id,
                product_detail_id=item.product_detail_id,
                quantity=item.quantity,
                unit_price=unit_price,
            )
            db.session.add(quotation_item)

        # 清空购物车
        QuotationCartItem.query.filter_by(cart_id=cart.id).delete()
        db.session.commit()

        return jsonify(
            {
                "success": True,
                "message": "报价单生成成功",
                "quotation_number": quotation_number,
                "quotation_url": url_for("view_quotation", quotation_id=quotation.id),
            }
        )
    except Exception as e:
        db.session.rollback()
        return jsonify({"success": False, "message": f"生成失败：{str(e)}"}), 500


@cart_bp.route("/quotation/<int:quotation_id>")
@login_required
def view_quotation(quotation_id):
    quotation = Quotation.query.get_or_404(quotation_id)
    if quotation.user_id != current_user.id:
        return jsonify({"success": False, "message": "无权限查看此报价单"}), 403
    items = QuotationItem.query.filter_by(quotation_id=quotation_id).all()
    return render_template("cart/view_quotation.html", quotation=quotation, items=items)
